/**
  * <br>JAVACC DEMO 1.0<br>
*/
package com.apache.portal.weixin.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apache.portal.weixin.core.common.LoadService;
import com.apache.portal.weixin.core.manager.BeanFactory;
import com.apache.portal.weixin.entity.send.WxSendMsg;
import com.apache.tools.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
  * description: 对接微信统一入口action
  * @author Hou DaYu 创建时间：上午08:45:17
  */
@SuppressWarnings("serial")
public class WeixinAction extends HttpServlet {
	protected Logger log = LoggerFactory.getLogger(this.getClass().getName());
	/**
	 * get请求进行验证服务器是否正常
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 进行接口验证
		 */
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = StrUtil.doNull(request.getParameter("echostr"), "ok");
		log.info("signature-->"+signature);
		log.info("timestamp-->"+timestamp);
		log.info("nonce-->"+nonce);
		log.info("echostr-->"+echostr);
		if (null != timestamp && null != nonce && null != signature && null != echostr) {
			if (LoadService.getInstance().getTools().access(signature, timestamp, nonce)) {
				log.info("response-->"+echostr);
				response.getWriter().write(echostr);
				return;
			}
			response.getWriter().write(echostr);
			return;
		} else {
			return;
		}
	}

	/**
	 * post请求接受用户输入的消息，和消息回复
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		try {
			WxSendMsg sendMsg = BeanFactory.getInstance().getCoreService().processRequest(request);
			LoadService.getInstance().getTools().send(sendMsg, response.getOutputStream());
			return;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
